package controllers

import java.io.File
import java.nio.file.Files

import config.{Global, MyFile}
import javax.inject.{Inject, Singleton}
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents, Headers}

import scala.concurrent.ExecutionContext

@Singleton
class ImagesController @Inject()(cc: ControllerComponents
                               )(implicit exec: ExecutionContext)
  extends AbstractController(cc)  with MyFile{


  def getOgImage(name: String) = Action { implicit request =>
    val path = s"og/img/${name.replaceAll("\\\\","").replaceAll("/","")}"
    val file =  s"${Global.path}/$path".toFile
    SendImg(file, request.headers)
  }


  def getBurdockImage(name: String) = Action { implicit request =>
    val path = s"config/uplc/burdock/${name.replaceAll("\\\\","").replaceAll("/","")}"
    val file =  s"${Global.path}/$path".toFile
    SendImg(file, request.headers)
  }

  def gePericarpImage(name: String) = Action { implicit request =>
    val path = s"config/uplc/pericarp/${name.replaceAll("\\\\","").replaceAll("/","")}"
    val file =  s"${Global.path}/$path".toFile
    SendImg(file, request.headers)
  }

  def geKernelImage(name: String) = Action { implicit request =>
    val path = s"config/uplc/kernel/${name.replaceAll("\\\\","").replaceAll("/","")}"
    val file =  s"${Global.path}/$path".toFile
    SendImg(file, request.headers)
  }

  def geVarietiesImage(name: String) = Action { implicit request =>
    val path = s"config/varietiesImage/${name.replaceAll("\\\\","").replaceAll("/","")}.jpeg"
    val file =  s"${Global.path}/$path".toFile
    if(file.exists()){
      SendImg(file, request.headers)
    }else{
      SendImg( s"${Global.path}/config/varietiesImage/null.jpeg".toFile, request.headers)
    }
  }

  def getPhoto(img: String) = Action { implicit request =>
    val file = s"${Global.path}/config/img/${img}_7.jpg".toFile
    println(file.getPath)
    if(file.exists()) {
      SendImg(file, request.headers)
    }else{
      SendImg( s"${Global.path}/config/null.jpg".toFile, request.headers)

    }
  }

  def getPhoto2(img: String) = Action { implicit request =>
    val file = s"${Global.path}/config/img/${img}".toFile
    if (file.exists()) {
      SendImg(file, request.headers)
    } else {
      SendImg(s"${Global.path}/config/null.jpg".toFile, request.headers)

    }
  }


  def SendImg(file: File, headers: Headers) = {
    val lastModifiedStr = file.lastModified().toString
    val MimeType = "image/jpg"
    val byteArray = Files.readAllBytes(file.toPath)
    val ifModifiedSinceStr = headers.get(IF_MODIFIED_SINCE)
    if (ifModifiedSinceStr.isDefined && ifModifiedSinceStr.get == lastModifiedStr) {
      NotModified
    } else {
      Ok(byteArray).as(MimeType).withHeaders(LAST_MODIFIED -> file.lastModified().toString)
    }
  }





}

